package com.kedacom.ctsp.authz.oauth2.client.provider;

import com.kedacom.ctsp.authz.security.AuthzSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @com.kedacom.ctsp.authz.oauth2.client.provider
 * @fenghaiju
 * @2018/5/14-16:37
 * @cloud-rbac
 **/
@Slf4j
public class RequestClientFilter extends OncePerRequestFilter {
    private static final String RETURN_URI = "returnUri";
    @Autowired
    private AuthzSecurityProperties securityProperties;
    private RequestCache requestCache = new HttpSessionRequestCache();

    /**
     * 是否需要过滤
     *
     * @param url
     * @return
     */
    private boolean isInclude(String url) {
        Matcher matcher = Pattern.compile(securityProperties.getLoginTokenUrl()).matcher(url);
        return matcher.matches();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        if(savedRequest == null){
            filterChain.doFilter(request, response);
            return;
        }
        String targetUrl = savedRequest.getRedirectUrl();
        if (savedRequest == null) {
            targetUrl = request.getRequestURL().toString();
        }
        log.info("return_url:", targetUrl);
        request.setAttribute(RETURN_URI, targetUrl);
        filterChain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return isInclude(request.getServletPath());
    }
}
